<template>
    <div class="ui-address">
        <UiSelect :option="data.provinceOption" v-model="data.province" @getItem="getProvince" placeholder="请选择省份"/>
        <UiSelect :option="data.cityOption" v-model="data.city" @getItem="getCity" placeholder="请选择市"/>
        <UiSelect :option="data.countyOption" v-model="data.county" @getItem="updateAddress" placeholder="请选择区/县"/>
    </div>
</template>
<script setup name="uiSelectAddress">
import { reactive, ref, defineProps, defineEmits, onMounted } from 'vue';
import addressData from '../libs/addressData';
import UiSelect from '../select/select.vue'
const AD = addressData
let provinceData = AD[86]
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
// 转数组
const handleListData = (data) => {
    let list = []
    for (let key in data) {
        list.push({label: data[key], value: key})
    }
    return list
}
// 向外部更新数据
const updateAddress = () => emit('update:modelValue', [data.province, data.city, data.county])
        
// 响应式数据
const data = reactive({
    province: ref(),
    city: ref(),
    county: ref(),
    provinceOption: handleListData(provinceData),
    cityOption: reactive([]),
    countyOption: reactive([])
})
// 获取省的选择 确定市数据
const getProvince = (e, type) => {
    data.cityOption = handleListData(AD[e.value]);
    data.city = ''
    data.county = ''
    data.countyOption = [];
    (type != 'noUpdate')&&updateAddress()
}
// 获取省的选择 确定市数据
const getCity = (e, type) => {
    data.countyOption = handleListData(AD[e.value]);
    data.county = '',
    (type != 'noUpdate')&&updateAddress()
}
// 挂载完毕后
onMounted(() => {
    let address = props.modelValue
    if(address){
        if(address[0]){
            for (let key in provinceData) {
                if(provinceData[key] == address[0]){
                    getProvince({value: key}, 'noUpdate')
                }
            }
            if(address[1]){
                (data.cityOption||[]).forEach(item => {
                    if(item.label == address[1]){
                        getCity({value: item.value}, 'noUpdate')
                    }
                })
            }
        }
        [data.province, data.city, data.county] = address;
    }
})
</script>